<?php namespace Install\Controller;

use Hdphp\Controller\Controller;

class IndexController extends Controller
{
    //步骤
    private $step;

    //构造函数
    public function __init()
    {
        if (is_file(MODULE_PATH.'/lock.php') && ACTION != 'isLock')
        {
            go('isLock');
        }
        $this->step = Q('step', 1, 'intval');
    }

    /**
     * 安装锁定后的提示页
     * @return boolean [description]
     */
    public function isLock()
    {
        $this->display();
        exit;
    }

    /**
     * 安装初始界面
     * @return [type] [description]
     */
    public function index()
    {
        $this->display();
    }

    /**
     * 版权信息页
     * @return [type] [description]
     */
    public function copyright()
    {
        $this->display();
    }

    /**
     * 环境检测
     */
    public function environment()
    {
        $this->safe = (ini_get('safe_mode') ? '<span class="hd-validate-error">Off</span>' : '<span class="hd-validate-success">On</span>');
        $this->gd = extension_loaded('GD') ? '<span class="hd-validate-success">On</span>' : '<span class="hd-validate-error">Off</span>';
        $this->curl = extension_loaded('CURL') ? '<span class="hd-validate-success">On</span>' : '<span class="hd-validate-error">Off</span>';
        $this->pdo = class_exists("Pdo") ? '<span class="hd-validate-success">On</span>' : '<span class="hd-validate-error">Off</span>';
        $this->mb_substr = function_exists("mb_substr") ? '<span class="hd-validate-success">On</span>' : '<span class="hd-validate-error">Off</span>';
        $this->mcrypt_encrypt = function_exists("mcrypt_encrypt") ? '<span class="hd-validate-success">On</span>' : '<span class="hd-validate-error">Off</span>';
        //检测目录
        $this->dirctory = array(
            '.', //网站根目录
            "config", //配置目录
            'public', //安装目录
            );
        $this->display();
    }

    /**
     * 数据库信息
     * @return [type] [description]
     */
    public function database()
    {
        $this->display();
    }

    /**
     * 设置数据库
     */
    private function UpdateTableData()
    {
        $db = Db::table('config');
        $db->where('name','WEBNAME')->update(array('value' => $_SESSION['_install']['WEBNAME']));
        $db->where('name','EMAIL')->save(array('value' => $_SESSION['_install']['EMAIL']));
        
        //站长信息
        $code = substr(md5(mt_rand() . time()), 0, 10);
        $data = array(
            'uid' => 1,
            'rid' => 1,
            'username' => $_SESSION['_install']['WEB_MASTER'],
            'nickname' => $_SESSION['_install']['WEB_MASTER'],
            'email' => $_SESSION['_install']['EMAIL'],
            'regtime' => time(),
            'code' => $code,
            'password' => md5($_SESSION['_install']['password'] . $code)
            );
        Db::table('user')->where('uid',1)->update($data);
    }

    /**
     * 还原数据表
     */
    public function InsertTableData()
    {
        //导入数据
        $db_prefix = Config::get('database.prefix');
        
        $db = Db::table('test');

        //创建结构
        require MODULE_PATH . "/Data/structure.php";

        foreach (glob(MODULE_PATH . "/Data/*") as $f)
        {
            if (preg_match('@\d+\.php@', $f))
            {
                require $f;
            }
        }

        //更新配置表
        $this->UpdateTableData();

        $this->success('数据表创建成功');
    } 

    /**
     * 验证数据库连接参数
     */
    public function VerifyDatabaseParam()
    {
        if(IS_AJAX)
        {
            if (empty($_POST['WEB_MASTER']))
            {
                $this->error('管理员帐号不能为空');
            }
            if (empty($_POST['admin_password']))
            {
                $this->error('管理员密码不能为空');
            }
            if (empty($_POST['WEBNAME']))
            {
                $this->error('网站名称不能为空');
            }
            if (!preg_match('/.+@.+\..+/',$_POST['EMAIL']))
            {
                $this->error('邮箱格式错误');
            }

            //连接服务器
            if (!@mysql_connect($_POST['host'], $_POST['user'], $_POST['password']))
            {
                $this->error('数据库连接失败');
            }
            
            //创建数据库
            if (!@mysql_query("CREATE DATABASE IF NOT EXISTS " . $_POST['database'] . " CHARSET UTF8"))
            {
                $this->error('创建数据库失败');
            }

            //更新配置文件后，需要重新请求一下，才可以将数据库配置应用至项目
            $_SESSION['_install']=$_POST;

            //更新数据库配置文件
            $config = <<<str
<?php
return array(
    'read'=>array(),
    'write'=>array(),
    'host'              =>'{$_POST['host']}',       //主机
    'driver'            => 'mysql',                 //数据库类型
    'charset'           => 'utf8',                  //数据库字符集
    'user'              => '{$_POST['user']}',      //数据库用户名
    'password'          => '{$_POST['password']}',  //数据库密码
    'database'          => '{$_POST['database']}',  //数据库名称
    'prefix'            => '{$_POST['prefix']}',    //表前缀
);
str;
            if (!file_put_contents('config/database.php', $config))
            {
                $this->error('创建配置文件失败');
            }

            //保存超级管理员等信息
$web=<<<str
<?php
return array(
    'WEB_MASTER'    =>'{$_POST['WEB_MASTER']}'
);
str;
            file_put_contents('config/web.php', $web);
            $this->success('验证通过');
        }
    }

    //安装完成
    public function Complete()
    {
        $this->display();
        touch(MODULE_PATH.'/lock.php');
    }
}